/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.ekuma.epos.businesslogic;

import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import com.openbravo.bean.AppUser;
import com.openbravo.data.loader.LocalRes;

import com.openbravo.pos.util.StringUtils;
import com.openbravo.bean.shard.UserOrderTypePermission;
import com.openbravo.bean.shard.UserPermission;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.ofsm.IEvent;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Administrator
 */
public class RoleUtil {
   public static String Permission_CHANGE_TICKET_RATE="sales.ChangeTicketRate";
   public static String Permission_EDIT_TICKET_LINE="sales.EditLines";
   public static String Permission_CHANGE_TICKET_TYPE="sales.RefundTicket";
   public static String Permission_ADD_CUSTOMER="sales.AddCustomer";
   public static String Permission_PRINT_TICKET="sales.PrintTicket";
   public static String Permission_OPENDRAWER="button.opendrawer";
   public static String Permission_SHOW_BUY_PRICE="sales.showBuyPrice";


   private static Logger logger = Logger.getLogger("com.openbravo.pos.forms.AppUser");

   private static SAXParser m_sp = null;
   private static HashMap<String, String> m_oldclasses; // This is for backwards compatibility purposes

   public static List<UserPermission> fillPermissions(I_DataLogicSystem dlSystem,String m_sRole) {
        String sRolePermisions = dlSystem.findRolePermissions(m_sRole);
        return formatPermissions(sRolePermisions);
     }

    public static List<UserPermission> fillPermissionsByAdvCode(I_DataLogicSystem dlSystem,String advCode) {
        String sRolePermisions = dlSystem.findRolePermissionsByAdvCode(advCode);
        return formatPermissions(sRolePermisions);
     }

   public static List<UserPermission> formatPermissions(String sRolePermisions) {
        // inicializamos los permisos
       List<UserPermission> m_apermissions = new ArrayList<UserPermission>();
       m_apermissions.add(new UserPermission(1000,"com.openbravo.pos.forms.JPanelMenu",UserPermission.PERMISSIONGROUP_System));
       m_apermissions.add(new UserPermission(1001,"Menu.Exit",UserPermission.PERMISSIONGROUP_System));
        if (sRolePermisions != null) {
            try {
                if (m_sp == null) {
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    m_sp = spf.newSAXParser();
                }
              StringReader ss=  new StringReader(sRolePermisions);
              ConfigurationHandler configHandler=new ConfigurationHandler(m_apermissions);
              m_sp.parse(new InputSource(ss), configHandler);
            } catch (ParserConfigurationException ePC) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
            } catch (SAXException eSAX) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
            } catch (IOException eIO) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
            }
        }
        return m_apermissions;
     }

    public static String buildXml(List<UserPermission> permissions){
        String retStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
               retStr+="<permissions>";
       for(UserPermission item:permissions)
            retStr+="<class "+"id=\""+item.getId()+"\" name=\""+item.getPermission()+"\" group=\""+item.getGroup()+"\"/>";
        retStr+="</permissions>";
        return retStr;
    }

    private static class ConfigurationHandler extends DefaultHandler {
         List<UserPermission> apermissions;
        public ConfigurationHandler( List<UserPermission> m_apermissions){
            apermissions=m_apermissions;
        }
        @Override
        public void startDocument() throws SAXException {}
        @Override
        public void endDocument() throws SAXException {}
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
            if ("class".equals(qName)){
            	String value=attributes.getValue("id");
                UserPermission temp=new UserPermission(value==null?9999:Integer.valueOf(value),attributes.getValue("name"));
                temp.setGroup(attributes.getValue("group"));
                apermissions.add(temp);
            }
        }
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {}
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {}
    }

    static {
        initOldClasses();
    }

    private static String mapNewClass(String classname) {
        String newclass = m_oldclasses.get(classname);
        return newclass == null
                ? classname
                : newclass;
    }

    private static void initOldClasses() {
        m_oldclasses = new HashMap<String, String>();
    }

    public static Map<String,UserOrderTypePermission> formatOrderTypePermissions(String sRolePermisions){
        // inicializamos los permisos
       Map<String,UserOrderTypePermission> m_apermissions = new HashMap<String,UserOrderTypePermission>();
       if (sRolePermisions != null) {
            try {
                if (m_sp == null) {
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    m_sp = spf.newSAXParser();
                }
              StringReader ss=  new StringReader(sRolePermisions);
              OrderTypePermissionHandler configHandler=new OrderTypePermissionHandler(m_apermissions);
              m_sp.parse(new InputSource(ss), configHandler);
            } catch (ParserConfigurationException ePC) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
            } catch (SAXException eSAX) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
            } catch (IOException eIO) {
                logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
            }
        }
        return m_apermissions;
     }

    private static class OrderTypePermissionHandler extends DefaultHandler {
        Map<String,UserOrderTypePermission> apermissions;
        public OrderTypePermissionHandler(Map<String,UserOrderTypePermission> m_apermissions){
            apermissions=m_apermissions;
        }
        @Override
        public void startDocument() throws SAXException {}
        @Override
        public void endDocument() throws SAXException {}
        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException{
            if ("orderTypePermission".equals(qName)){
                UserOrderTypePermission temp=new UserOrderTypePermission(attributes.getValue("orderTypeID"));
                temp.setGrantEvents(splitProp(attributes.getValue("Events")));
                apermissions.put(temp.getOrderTypeID(),temp);
            }
        }
        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {}
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {}
    }

    public static String buildOrderTypePermissionXml(java.util.Collection<UserOrderTypePermission> permissions){
        String retStr="<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
               retStr+="<orderTypePermissions>";
       for(UserOrderTypePermission item:permissions){
           if(!item.getGrantEvents().isEmpty())
              retStr+="<orderTypePermission orderTypeID=\""+item.getOrderTypeID()+"\" Events=\""+mergeProp(item.getGrantEvents())+"\"/>";
       }
        retStr+="</orderTypePermissions>";
        return retStr;
    }

    private static ArrayList<String> splitProp(String prop){
       ArrayList<String> propList=new ArrayList<String>();
       if(prop==null||prop.isEmpty())
           return propList;
       String[] propEntry=prop.split(",");
       for(int i=0;i<propEntry.length;i++)
           propList.add(propEntry[i]);
       return propList;
   }

   private static String mergeProp(List<String> list){
       return  StringUtils.join(list.iterator(), ",");
   }
   /**
   public static String getLocalePermissionName(String name){
        return AppLocal.getIntString(name);
   }
   **/
    public static boolean authenticate(AppUser user) {
        return user.getPassword() == null || user.getPassword().equals("") || user.getPassword().startsWith("empty:");
    }

    public static void fillPermissions(AppUser user,I_DataLogicSystem dlSystem) {
        // inicializamos los permisos
        user.setM_apermissions(fillPermissions(dlSystem, user.getRole()));
    }

    public static boolean hasPermission(AppUser user,String classname) {
        return (user.getM_apermissions()== null) ? false : hasPermission(user,new UserPermission(0,classname));
    }

     public static boolean hasPermission(AppUser user,UserPermission permission){
        return user.getM_apermissions().contains(permission);
    }

     
     //----orderType----------
     public static Map<String,UserOrderTypePermission> fillOrderTypePermissions(I_DataLogicSystem dlSystem,String m_sRole) {
         String sRolePermisions = dlSystem.findRoleOrderTypePermissions(m_sRole);
         return formatOrderTypePermissions(sRolePermisions);
      }
     
    public static void fillOrderTypePermission(AppUser user,I_DataLogicSystem dlSystem){
        user.setOrderTypePermissions(fillOrderTypePermissions(dlSystem, user.getRole()));
    }

    public static boolean hasOrderTypePermission(AppUser user,String orderTypeId,String event){
        UserOrderTypePermission permission=user.getOrderTypePermissions().get(orderTypeId);
        if(permission!=null&&permission.getGrantEvents().contains(event))
            return true;
        return false;
    }
    
    public static List<IEvent> filterUserOrderTypeEvents(AppUser m_appuser,
			String id, List<IEvent> transitionEventByCurrentState) {
		 List<IEvent> rets=new ArrayList();
	        for(IEvent e:transitionEventByCurrentState)
	            if(hasOrderTypePermission(m_appuser,id,e.getName()))
	                rets.add(e);
	        return rets;
	}
    
    
    //---------stateProcess----------
    
    public static Map<String,UserOrderTypePermission> fillUserStateProcessPermissions(I_DataLogicSystem dlSystem,String m_sRole) {
        String sRolePermisions = dlSystem.findUserStateProcessPermissions(m_sRole);
        return formatOrderTypePermissions(sRolePermisions);
     }
    
    public static void fillUserStateProcessPermission(AppUser user,I_DataLogicSystem dlSystem){
        user.setUserStateProcessPermissions(fillUserStateProcessPermissions(dlSystem, user.getRole()));
    }

    public static boolean hasUserStateProcessPermission(AppUser user,String processId,String event){
        UserOrderTypePermission permission=user.getUserStateProcessPermissions().get(processId);
        if(permission!=null&&permission.getGrantEvents().contains(event))
            return true;
        return false;
    }

    public static List<IEvent> filterUserStateProcessEvents(AppUser user,String processId,List<IEvent> filterEvents){
        List<IEvent> rets=new ArrayList();
        for(IEvent e:filterEvents)
            if(hasUserStateProcessPermission(user,processId,e.getName()))
                rets.add(e);
        return rets;
    }

}
